package com.gzy.studentsociety.web;

import com.gzy.studentsociety.dao.SocietyDao;
import com.gzy.studentsociety.dao.SocietyDaolmpl;
import com.gzy.studentsociety.dao.SocietyDaolmpl;
import com.gzy.studentsociety.dao.StudentDao;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Society;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet(name = "SocietyServlet", value = "/society/*")
public class SocietyServlet extends RouteServlet {
    private SocietyDao societyDao = new SocietyDaolmpl();
    private StudentDao studentDao = new StudentDaoImpl();
    @Override
    protected Class<?> getMyClass() {
        return this.getClass();
    }

    public String mainIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Society> list;
        try {
            list = societyDao.getAllSociety();
            list = list.stream().map(i -> {
                try {
                    i.setCreator(studentDao.findById(i.getSociety_creator()));
                } catch (SQLException e) {
                    request.setAttribute("exception", e);
                }
                return i;
            }).collect(Collectors.toList());
        } catch (SQLException e) {
            handleException(e, request, response);
            return "error";
        }
        request.setAttribute("societies", list);
        return "mainIndex";
    }

    public String addSociety(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");
        System.out.println("Received name: " + name);
        System.out.println("Received intro: " + intro);

        Society society = new Society();
        society.setSociety_intro(intro);
        society.setSociety_name(name);
        society.setSociety_status(1);

        String number = (String) req.getSession().getAttribute("student");
        try {
            society.setSociety_creator(studentDao.findByNumber(number).getStudentId());
        } catch (SQLException e) {
            handleException(e, req, res);
            return "error";
        }

        society.setSociety_create_date(new Date());

        try {
            societyDao.insertSociety(society);
            res.sendRedirect("/studentSociety/society/mainIndex");
            return "direct"; // Optional, since sendRedirect doesn't return control
        } catch (SQLException e) {
            handleException(e, req, res);
            return "error";
        }
    }
    public Map<String, Object> updateSociety(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String idStr = req.getParameter("id");
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");

        Map<String, Object> responseMap = new HashMap<>();
        Integer id = idStr != null ? Integer.valueOf(idStr) : null;

        if (id == null) {
            responseMap.put("message", "Invalid ID");
            return responseMap;
        }

        Society society = new Society();
        society.setSocietyId(id);
        society.setSociety_name(name);
        society.setSociety_intro(intro);

        try {
            int result = societyDao.updateSociety(society);
            responseMap.put("message", result);
        } catch (SQLException e) {
            responseMap.put("message", e.getMessage());
        }
        return responseMap;
    }

    public Map<String, Object> changeStatus(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String idStr = req.getParameter("id");
        String statusStr = req.getParameter("status");

        Map<String, Object> responseMap = new HashMap<>();

        try {
            Integer id = Integer.valueOf(idStr);
            Integer status = Integer.parseInt(statusStr);
            Society society = new Society();
            society.setSocietyId(id);
            society.setSociety_status(status);

            int result = societyDao.updateSociety(society);
            responseMap.put("result", result == 1 ? "Status updated" : "Failed to update status");
        } catch (SQLException e) {
            req.setAttribute("exception", e);
            responseMap.put("error", "Database error");
        } catch (NumberFormatException e) {
            responseMap.put("error", "Invalid number format");
        }
        return responseMap;
    }
    public Object addPage(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String number = (String) session.getAttribute("student");
        Society society = null;
        try {
            society = societyDao.queryByStudentNumber(number);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables, req, res);
        }
        req.setAttribute("society", society);
        return "member/addStudent";
    }
}

